using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Services;
using FreeLancer.HRB.Domains;
using FreeLancer.HRB.Core;
using FreeLancer.HRB.Core.Services;
using System.IO;
using DevExpress.Web.ASPxUploadControl;

namespace FreeLancer.HRB.WebApp.UserControls
{
  public partial class EditPage : System.Web.UI.UserControl
  {
    #region Members

    private FreeLancer.HRB.Domains.Page _page;
    private int _languageId;

    private Guid _id = Guid.Empty;
    /// <summary>
    /// Determine what content of page to be display
    /// </summary>
    public Guid Id
    {
      get { return _id; }
      set { _id = value; }
    }

    DateTime now = DateTime.Now;

    #endregion

    #region Page Events

    protected void Page_Init(object sender, EventArgs e)
    {
      //string path = "./"; //Utils.AbsoluteWebRoot.AbsoluteUri.Replace("~/", "");
      //ASPxHtmlEditor.SettingsImageUpload.UploadImageFolder =
      //  path + "Images/PageImages/";
      LoadLanguage();

      if (cboLanguage.Items.Count > 0)
        _languageId = int.Parse(cboLanguage.Items[0].Value);
      else
        _languageId = 0;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        InitializePageContent();
        EnabledAttachedFile();
      }

      lblErrorUpdateFailed.Visible = false;
    }

    #endregion

    #region Control Events

    protected void cboLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
      InitializePageContent();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
      PageService pageService = GlobalCache.PageServiceInstance;
      
      GetPageContent();

      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          pageService.Save(_page);
          if (ConnectionScope.Complete())
          {
            lblTime.Text = _page.DateModified.ToString();
          }
          else
          {
            LoggingService.LogError("EditPage control", "Can not complete transaction when saving Page.",
              null, LoggingService.DefaultCategory, true);

            lblErrorUpdateFailed.Visible = true;
          }
        }
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("EditPage control", "Can not save Page.", ex,
              LoggingService.DefaultCategory, true);

        lblErrorUpdateFailed.Visible = true;
      }
    }

    #endregion

    #region Page Processing

    /// <summary>
    /// Initialize language to combobox
    /// </summary>
    private void LoadLanguage()
    {
      int total = 0;
      LanguagesService languageService = new LanguagesService();
      TList<Languages> languages = languageService.GetPaged("IsActive='True'", string.Empty, 0, 3, out total);
      cboLanguage.DataSource = languages;
      cboLanguage.DataTextField = "Name";
      cboLanguage.DataValueField = "LanguageID";
      cboLanguage.DataBind();
    }

    /// <summary>
    /// Load Page
    /// </summary>
    private void LoadPage()
    {
      if (!string.IsNullOrEmpty(cboLanguage.SelectedValue))
      {
        _languageId = int.Parse(cboLanguage.SelectedValue);
      
        int total = 0;

        PageService pageService = GlobalCache.PageServiceInstance;
        TList<FreeLancer.HRB.Domains.Page> pages = 
          pageService.GetPaged("PageID='" + _id + "' AND LanguageID=" + _languageId, 
          string.Empty, 0, 3, out total);

        _page = pages.Find(PageColumn.LanguageId, _languageId);

        lblErrorLoadFailed.Visible = false;
      }

      if (_page == null)
      {
        lblErrorLoadFailed.Visible = true;
        lblTime.Visible = false;

        LoggingService.LogError("EditPage control", "Can not load data for Page: PageID=" + _id,
              null, LoggingService.DefaultCategory, true);
      }
    }

    /// <summary>
    /// Load Page content
    /// </summary>
    private void InitializePageContent()
    {
      LoadPage();

      if (_page != null)
      {
        txtTitle.Text = _page.Title;
        ASPxHtmlEditor.Html = _page.PageContent;
        lblTime.Text = _page.DateModified.ToString();
      }
    }

    /// <summary>
    /// Put data to Page
    /// </summary>
    private void GetPageContent()
    {
      LoadPage();

      if (_page != null)
      {
        _page.Title = txtTitle.Text;
        _page.DateModified = DateTime.Now;
        _page.PageContent = ASPxHtmlEditor.Html;

        if ((chkUploadedFile.Visible == false) && (string.IsNullOrEmpty(linkUploadedFile.Text)))
        {
          if (!string.IsNullOrEmpty(ASPxUploadControlFile.FileName))
            _page.AttachedPath = now.ToString("yyyyMMddhhmmss") + "_" + ASPxUploadControlFile.FileName;
          else
            _page.AttachedPath = null;
        }
        else
        {
          if (chkUploadedFile.Checked == false)
          {
            if (_page.AttachedPath != null)
            {
              try
              {
                File.Delete(Server.MapPath("~/Files/PageFiles/") + _page.AttachedPath);
              }
              catch (Exception ex)
              {
                LoggingService.LogCritical("Admin-EditPage Page", "Can not delete attached file.", ex,
                  LoggingService.DefaultCategory, true);
              }
              _page.AttachedPath = null;
            }
          }
        }
      }
      EnabledAttachedFile();
    }

    private void EnabledAttachedFile()
    {
      if (string.IsNullOrEmpty(_page.AttachedPath))
      {
        ASPxUploadControlFile.Visible = true;
        linkUploadedFile.Visible = false;
        chkUploadedFile.Visible = false;
        chkUploadedFile.Checked = false;
      }
      else
      {
        ASPxUploadControlFile.Visible = false;
        linkUploadedFile.Visible = true;
        chkUploadedFile.Visible = true;
        chkUploadedFile.Checked = true;
        linkUploadedFile.Text = _page.AttachedPath.Substring(_page.AttachedPath.IndexOf('_') + 1);
        linkUploadedFile.NavigateUrl =
          Utils.RelativeWebRoot + "Files/PageFiles/" + _page.AttachedPath;
      }
    }

    #endregion

    #region Upload

    protected void ASPxUploadControlFile_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
    {
      if (e.IsValid)
      {
        string path = Server.MapPath("~/Files/PageFiles/");

        path = path + now.ToString("yyyyMMddhhmmss") + "_" + ASPxUploadControlFile.FileName;

        ASPxUploadControlFile.SaveAs(path, true);
      }
    }

    #endregion
  }
}